import { resolve, sep } from "path";
import { fileURLToPath } from "url";

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import vueJsx from "@vitejs/plugin-vue-jsx";
import { prismjsPlugin } from "vite-plugin-prismjs";
import Components from "unplugin-vue-components/vite";
import AutoImport from "unplugin-auto-import/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";

const __dirname = fileURLToPath(new URL(".", import.meta.url));

const MONACO_EDITOR_PREFIX = "monaco-editor/esm/vs";
const LAST_UPDATE_TIME = Date.now();

// https://vitejs.dev/config/
export default defineConfig(({ mode, command, ssrBuild }) => {
  console.log("mode: ", mode);
  console.log("command: ", command);

  return {
    plugins: [
      vue(),
      vueJsx(),
      Components({
        dirs: ["src/components", "src/pages"],
        resolvers: [ElementPlusResolver()]
      }),
      AutoImport({
        resolvers: [ElementPlusResolver()]
      }),
      prismjsPlugin({
        // markdown 语言包
        languages: ["ts", "js", "json", "sh", "rust"]
      })
    ],
    base: "./",
    define: {
      __LAST_UPDATE_TIME__: LAST_UPDATE_TIME,
      __APP_DIRNAME__: __dirname.split(sep)
    },
    resolve: {
      alias: [
        {
          find: "@",
          replacement: resolve(__dirname, "src")
        },
        {
          find: "root",
          replacement: resolve(__dirname, "./")
        }
      ]
    },

    // tauri
    server: {
      host: true,
      port: 8081,
      // open: true,
      // Tauri 使用固定端口，若此端口不可用将会导致程序错误
      strictPort: true
      // hmr: {
      // 	overlay: false
      // }
    },
    // 防止 vite 输出复杂的 rust 错误
    clearScreen: false,
    // 使用 `TAURI_PLATFORM`、`TAURI_ARCH`、`TAURI_FAMILY`,
    // `TAURI_PLATFORM_VERSION`、`TAURI_PLATFORM_TYPE` 和 `TAURI_DEBUG` 环境变量
    envPrefix: ["VITE_", "TAURI_"],
    build: {
      // Tauri 支持 es2021
      target: ["es2021", "chrome100", "safari13"],
      // 不为调试构建压缩构建体积
      minify: !process.env.TAURI_DEBUG ? "esbuild" : false,
      // 为调试构建生成源代码映射 (sourcemap)
      sourcemap: !!process.env.TAURI_DEBUG,

      // monaco-editor
      rollupOptions: {
        output: {
          manualChunks: {
            jsonWorker: [`${MONACO_EDITOR_PREFIX}/language/json/json.worker`],
            cssWorker: [`${MONACO_EDITOR_PREFIX}/language/css/css.worker`],
            htmlWorker: [`${MONACO_EDITOR_PREFIX}/language/html/html.worker`],
            tsWorker: [`${MONACO_EDITOR_PREFIX}/language/typescript/ts.worker`],
            editorWorker: [`${MONACO_EDITOR_PREFIX}/editor/editor.worker`]
          }
        }
      }
    }
  };
});
